# -*- coding: utf-8 -*-
# @Author: Wolf
# @Date:   2025-03-21 10:50:33
# @Last Modified by:   Wolf
# @Last Modified time: 2025-03-24 18:08:12
from django.shortcuts import render,redirect
from app01 import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError 
from django.utils.safestring import mark_safe
# Create your views here.


def depart_list(request):
    """部门列表"""
    queryset = models.Department.objects.all()

    return render(request, 'depart_list.html',{'queryset': queryset})



def depart_add(request):
    if request.method == 'GET':
        return render(request, 'depart_add.html')
    title = request.POST.get('title')

    models.Department.objects.create(title=title)
    return redirect('/depart/list/')

def depart_delete(request):
    nid=request.GET.get('nid')
    models.Department.objects.filter(id=nid).delete()
    return redirect('/depart/list/')


def depart_edit(request,nid):
    if request.method == "GET":
        row_object = models.Department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html',{"row_object": row_object})
    title = request.POST.get('title')
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list/')

def user_list(request):
    queryset = models.UserInfo.objects.all()
    # for obj in queryset:
    #     print(obj.id, obj.name, obj.account, obj.create_time.strftime("%Y-%m-%d"), obj.gender, obj.get_gender_display(), obj.depart.title)
    return render(request, 'user_list.html',{"queryset":queryset})


def user_add(request):
    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html',context)
    user = request.POST.get('name')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('ac')
    ctime = request.POST.get('ctime')
    gender = request.POST.get('gd')
    depart_id = request.POST.get('dp')
    models.UserInfo.objects.create(name=user, password=pwd, age=age,
                                   account=account, create_time=ctime,
                                   gender=gender, depart_id=depart_id)
    return redirect("/user/list/")


class UserModelForm(forms.ModelForm):
    class Meta:
        model = models.UserInfo
        fields = ['name','password','age','create_time',"gender","depart"]
        # widgets = {
        #     "name":forms.TextInput(attrs={"class":"form-control"}),
        #     "password":forms.PasswordInput(attrs={"class":"form-control"}),
        #     "age":forms.TextInput(attrs={"class":"form-control"}),
        #     "create_time":forms.TextInput(attrs={"class":"form-control"}),
        #     "gender":forms.Select(attrs={"class":"form-control"}),
        #     "depart":forms.Select(attrs={"class":"form-control"}),
        # }
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        for name,field in self.fields.items():
            field.widget.attrs = {"class":"form-control","placeholder":field.label}
            
def user_model_form_add(request):
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_model_form_add.html',{"form":form})
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    
    
    return render(request, 'user_model_form_add.html',{"form":form})

def user_edit(request,nid):
    row_object= models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserModelForm(instance = row_object)
        return render(request, 'user_edit.html',{'form':form})
    
    form = UserModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html',{"form":form})


def user_delete(request,nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')


def pretty_list(request):
    # for i in range(300):
    #     models.PrettyNum.objects.create(mobile="13812345671",price=10,level=1,status=1)
    data_dict={}
    search_data =request.GET.get('q',"")
    if search_data:
        data_dict['mobile__contains']=search_data
        
    page = int(request.GET.get('page',1))
    page_size = 10
    start = (page-1)*page_size
    end = page*page_size
    
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by('-level')[start:end]

    total_count = models.PrettyNum.objects.filter(**data_dict).order_by('-level').count()
    total_page_count, div = divmod(total_count,page_size)
    if div:
        total_page_count += 1

    plus = 5
    if total_page_count <= plus*2+1:
        start_page = 1
        end_page = total_page_count + 1
    else:
        if page <= plus:
            start_page = 1
            end_page = plus*2+1
        else:
            if (page + plus) > total_page_count:
                start_page = total_page_count - plus*2
                end_page = total_page_count + 1
            else:
                start_page = page - plus
                end_page = page +plus+1

    page_str_list=[]

    page_str_list.append('<li><a href="?page=1">首页</a></li>') 

    if page >1:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(page-1)
    else:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(1)
    page_str_list.append(prev)

    for i in range(start_page,end_page):
        if i == page:
            ele = '<li class="active"><a href="/pretty/list/?page={}">{}</a></li>'.format(i,i)
        else:
            ele = '<li><a href="/pretty/list/?page={}">{}</a></li>'.format(i,i)
        page_str_list.append(ele)
    

    if page > total_page_count:
        prev = '<li><a href="?page={}">下一页</a></li>'.format(page+1)
    else:
        prev = '<li><a href="?page={}">下一页</a></li>'.format(total_page_count)
    page_str_list.append(prev)

    page_str_list.append('<li><a href="?page={}">尾页</a></li>'.format(total_page_count)) 

    page_string = mark_safe("".join(page_str_list))

    return render(request, 'pretty_list.html', {'queryset': queryset,"search_data":search_data,
                  "page_string":page_string})



class PrettyModelForm(forms.ModelForm):
    mobile = forms.CharField(label='号码',validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式错误')])
    class Meta:
        model = models.PrettyNum
        fields = ['mobile','price','level','status']
        # fields= "__all__"


    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class":"form-control","placeholder":field.label}





def pretty_add(request):

    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html',{"form":form})
    form = PrettyModelForm(data=request.POST)
    print(form)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    
    
    return render(request, 'pretty_add.html',{"form":form})


def pretty_delete(request,nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')



class PrettyEditModelForm(forms.ModelForm):
    # mobile = forms.CharField(disabled=True,label="号码")
    class Meta:
        model = models.PrettyNum
        fields = ['mobile','price','level','status']
        # fields= "__all__"


    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class":"form-control","placeholder":field.label}

    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")
        return txt_mobile


def pretty_edit(request,nid):
    row_object= models.PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        form = PrettyEditModelForm(instance = row_object)
        return render(request, 'pretty_edit.html',{'form':form})
    
    form = PrettyEditModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_edit.html',{"form":form})